﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace MyVideoPlayer.Behaviors
{
    public static class DataGridCellDoubleClickBehavior
    {
        public static readonly DependencyProperty DoubleClickCommandProperty =
            DependencyProperty.RegisterAttached(
                "DoubleClickCommand",
                typeof(ICommand),
                typeof(DataGridCellDoubleClickBehavior),
                new PropertyMetadata(null, OnDoubleClickCommandChanged));

        public static void SetDoubleClickCommand(DependencyObject element, ICommand value)
        {
            element.SetValue(DoubleClickCommandProperty, value);
        }

        public static ICommand GetDoubleClickCommand(DependencyObject element)
        {
            return (ICommand)element.GetValue(DoubleClickCommandProperty);
        }

        private static void OnDoubleClickCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is DataGridCell cell)
            {
                if (e.NewValue != null)
                {
                    cell.MouseDoubleClick += Cell_MouseDoubleClick;
                }
                else
                {
                    cell.MouseDoubleClick -= Cell_MouseDoubleClick;
                }
            }
        }

        private static void Cell_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (sender is DataGridCell cell)
            {
                var command = GetDoubleClickCommand(cell);
                if (command != null && command.CanExecute(cell.DataContext))
                {
                    command.Execute(cell.DataContext);
                }
            }
        }
    }
}